//
//  HYLStatusPictureView.swift
//  iOSwechat
//
//  Created by apple on 16/3/3.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import SDWebImage

// 最大列数
private let maxColumn = 3
// cell之间的间距
private let HYLStatusPictureViewCellMargin: CGFloat = 10
// cell 宽高
//private let HYLStatusPictureViewWH = UIScreen.width - 2 * StatusCellMargin - (CGFloat( maxColumn) - 1) *HYLStatusPictureViewCellMargin / CGFloat(maxColumn)
private let HYLStatusPictureViewWH = (UIScreen.width - 2 * StatusCellMargin - (CGFloat(maxColumn) - 1) * HYLStatusPictureViewCellMargin) / CGFloat(maxColumn)


private let HYLStatusPictureViewSize = CGSize(width: HYLStatusPictureViewWH, height: HYLStatusPictureViewWH)

// cellSize
private let ReuseIdentifier = "ReuseIdentifier"

class HYLStatusPictureView: UICollectionView {
    
    // MARK: - 属性
    // 微博数据
    var status: HYLStatus? {
        didSet{
        
            // 计算微博配图的大小
            let viewSize = calcViewSize()
        
            // 重新约束
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(viewSize)
            }
            // 刷新collectionView
            self.reloadData()
        }
    }
    
    
    //MARK: -计算配图的大小
    private func calcViewSize() -> CGSize{
        let count = status?.storePictureURLs?.count ?? 0
        print("HYLStatusPictureViewSize: \(HYLStatusPictureViewSize)")

        print("==========================================count:\(count)")
        
        // 没有图片
        if count == 0 {
            return CGSizeZero
        }
    
        
        // 1张图片
        if count == 1 {
            // 默认图片大小
            var size = CGSize(width: 180, height: 120)
            
            let imageUrlName = status?.storePictureURLs?.first?.absoluteString
            
            // 获取图片,有可能失败
            if let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(imageUrlName) {
                // 获取到图片的size
                size = image.size
            }
            
            // 判断图片太大或者太小
            if size.width < 40 {
                size.width = 40
            }
            
            if size.width > UIScreen.width * 0.5{
                size.width = UIScreen.width * 0.5
            }
            
            
            layout.itemSize = size
            layout.minimumInteritemSpacing = 0
            layout.minimumLineSpacing = 0
            return size
        }
        
        // 设置layout
        layout.itemSize = HYLStatusPictureViewSize
        layout.minimumLineSpacing = HYLStatusPictureViewCellMargin
        layout.minimumInteritemSpacing = HYLStatusPictureViewCellMargin
        
    
        // 情况1
        // 计算列数
        // 判断是否是4张,4张显示2列,其它情况判断个数是否大于最大列数,小于最大列数显示count列, 大于最大列数显示最大列数
        var column = maxColumn
        if count == 4 || count == 2 {
            column = 2
        }
        
        let row = (count + column - 1) / column
        
        // 计算宽度
        let width = CGFloat(column) * HYLStatusPictureViewWH + (CGFloat(column) - 1) * HYLStatusPictureViewCellMargin
        // 计算高度
        let height = CGFloat(row) * HYLStatusPictureViewWH + (CGFloat(row) - 1) * HYLStatusPictureViewCellMargin
        
        // print("==========================================count:\(count)--column:\(column)--row:\(row)--width:\(width)--height:\(height)")
        return CGSize(width: width, height: height)
    }

    // 布局
    let layout = UICollectionViewFlowLayout()

    
    init(){
        super.init(frame:CGRectZero,collectionViewLayout:layout)
        backgroundColor = UIColor.clearColor()
        
        // 设置数据源和代理
        self.dataSource = self
        self.delegate = self
        
        
        // 注册cell
        self.registerClass(HYLStatusPictureViewCell.self, forCellWithReuseIdentifier: ReuseIdentifier)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


// MARK: - collectionView的数据源方法
extension HYLStatusPictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.storePictureURLs?.count ?? 0
    }
    
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! HYLStatusPictureViewCell
        
//         cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.redColor() : UIColor.brownColor()
        // 如果失败说明服务器返回的数据有问题
//        let urlString = status?.pic_urls?[indexPath.item]["thumbnail_pic"] as! String
        let url = status?.storePictureURLs?[indexPath.item]
        
        cell.imageURL = url
        
        return cell
    }
}


// MARK: - 配图cell
class HYLStatusPictureViewCell : UICollectionViewCell {
    
    // MARK: - 属性
    var imageURL:NSURL?{
        didSet {
            // 获取图片
            bkgImageView.sd_setImageWithURL(imageURL)
            
            // 设置imageView的contentMode 设置为等比例缩放
            bkgImageView.contentMode = UIViewContentMode.ScaleAspectFill
            // 图片还需要裁剪
            bkgImageView.clipsToBounds = true
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func prepareUI(){
        
        // 1.添加控件
        contentView.addSubview(bkgImageView)
        // 2.创建约束
        bkgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        
    }

    // 懒加载图片
    private lazy var bkgImageView: UIImageView = UIImageView(image: nil)
}



